import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import './shopcart.scss'

import Checkboxbar from '../../components/checkboxbar'
import NumberInput from '../../components/numInput/index'
import Footer from '../../components/cart/footer'
import Price from '../../components/cart/price'

import Authorize from '../../components/authorize/authorize'

import { set as setGlobalData, get as getGlobalData } from '../../static/js/global_data'
import api from '../../service/api'
import common from '../../service/common'
import base from '../../static/js/base'
import { parse } from 'path'

export default class Index extends Component {
    config = {
        navigationBarTitleText: '购物车'
    }
    constructor() {
        super(...arguments)
        this.state = {
            selectAllStatus: true, //默认全选
            mainColor: '#f00',
            defColor: '#ddd',
            domainImg: getGlobalData("domainImg"),
            HasCartList: false,
            editState: false, //结算
            cids: '',
            footerData: {
                SaleUseInteger: '0', // 使用的积分
                cqsje: '0.00', // 差多少满足起送金额
                cxreductions: '0.00', //总的促销折扣价格
                dbje: '0.00', //打包金额
                orderprice: '0.00', //订单总金额
                orderyprice: '0.00', //优惠后总金额
                settleNum: 0, //结算数量
            },
            popupSaledata: [], // 活动弹窗数据
            mkid: '', //促销活动编号
            mkcid: '', //促销活动类型
            cartList: [],
        }
    }
    // authorize获取作用域
    getIsLogin(obj){
        if(obj){
            if(obj.C_MB_NO){ 
                this.loadFun()
            }else{
                obj.isLogin(() => {
                    this.loadFun()
                })
            }
        }
    }
    componentWillMount(obj) {
        common.getShopInfo((res) => {
            this.setState({
                shopInfo: res.model
            })
        })
        this.getIsLogin(obj)
    }
    loadFun(){
        common.getUserCart(this, null, (cartList, res) => {
            console.log('cartList=====================================================')
            console.log(cartList)
            console.log(res)
            cartList.map((item, i) => {
                item.select = this.state.selectAllStatus
                if (item.select) {
                    this.state.footerData.settleNum += item.num
                    this.state.cids += item.cartId + ','
                    this.state.footerData.orderprice =  parseFloat(this.state.footerData.orderprice)  +  parseFloat(item.curTotalPrice)
                    this.state.footerData.orderyprice = parseFloat(this.state.footerData.orderyprice) +  parseFloat(item.preTotalPrice)
                    this.state.footerData.cxreductions = parseFloat(this.state.footerData.cxreductions) +  parseFloat(item.disTotalPrice)
                }
                item.salemodelIndex = null //当前的促销活动索引 
                if(item.saledata && item.saledata.length > 0){
                    item.saledata.map((items,ix) => {
                        if(item.N_MARKING_ID == items.SaleId){
                            item.salemodelIndex = ix.toString()
                        }
                    })
                    if(!item.salemodelIndex){
                        item.salemodelIndex = '0'
                        item.N_MARKING_ID = item.saledata[0].SaleId
                    }
                }

            })
            console.log(this.state.footerData)
            this.state.cids = this.state.cids.substr(0, this.state.cids.length - 1)
            // const footerData = {
            //     SaleUseInteger: res.SaleUseInteger, 
            //     cqsje: res.cqsje, 
            //     cxreductions: res.cxreductions, 
            //     dbje: res.dbje, 
            //     orderprice: res.orderprice, 
            //     orderyprice: res.orderyprice, 
            //     settleNum: this.state.footerData.settleNum, 
            // }
            this.setState({
                cartList: cartList,
                footerData:  this.state.footerData,
                HasCartList: true,
                cids: this.state.cids
            })
        }) 
    }
    // 修改购物车商品活动
    changeSaledata(index){
        if(!this.state.cartList[index].saledata){return}
        this.state.popupSaledata = []
        this.state.cartList[index].saledata.map((item,i) => {
            this.state.popupSaledata.push(item.SaleName)
        })
        Taro.showActionSheet({
            itemList: this.state.popupSaledata,
        })
        .then((res) => {
            if(res.tapIndex || res.tapIndex == 0){
                res.index = res.tapIndex 
            }
            if(res.index == -1){return}
            this.state.cartList[index].salemodelIndex = res.index.toString()
            this.state.mkid = this.state.cartList[index].saledata[res.index].SaleId
            this.state.mkcid = this.state.cartList[index].saledata[res.index].SaleTypeNo //促销活动类型
            base.showLoading()
            console.log(this.state.cartList[index],'console.log(this.state.cartList[index])')
            common.changeCar(this,'801', this.state.cartList[index], this.state.cartList[index].num, 0,() => {
                this.setCartData(this.state.selectAllStatus,this.state.cartList)
                Taro.hideLoading()
            })
        })
        .catch((err) => {console.log(err.errMsg)})
    }
    // 点击复选框
    selectCheck(id, select) {
        const len = this.state.cartList.length
        let flag = 0;
        let selectAllStatus;
        this.state.footerData.settleNum = 0
        this.state.cids = ''
        this.state.footerData.orderprice = 0
        this.state.footerData.orderyprice = 0
        this.state.footerData.cxreductions = 0
        console.log(id)
        this.state.cartList.map((item, i) => {
            if (id == 'all') { //全选
                item.select = !this.state.selectAllStatus
                selectAllStatus = !this.state.selectAllStatus
            }else {
                if (id == i) { item.select = !item.select }
                if (item.select == true) { flag++ }
                selectAllStatus = flag == len ? true : false
            }
            if (item.select) {
                this.state.footerData.settleNum += item.num
                this.state.cids += item.cartId + ','
                this.state.footerData.orderprice +=    parseFloat(item.curTotalPrice)
                this.state.footerData.orderyprice +=   parseFloat(item.preTotalPrice)
                this.state.footerData.cxreductions +=   parseFloat(item.disTotalPrice)
            }
        })
        this.setCartData(selectAllStatus,this.state.cartList)
    }
    // 点击加减购物车
    changeCartNum(index,bNo,types, e){
        console.log(index + ',' + bNo + ',' + types  + ',' + e)
        this.state.mkid = this.state.cartList[index].salemodelIndex ? this.state.cartList[index].saledata[this.state.cartList[index].salemodelIndex].SaleId : '';
        this.state.mkcid = this.state.cartList[index].salemodelIndex ? this.state.cartList[index].saledata[this.state.cartList[index].salemodelIndex].SaleTypeNo : '' //促销活动类型
        common.setCartList(this,'cart',index,bNo,types,(cartList) => {
            // console.log(cartList)
            this.state.footerData.settleNum = 0
            this.state.cids = ''
            this.state.footerData.orderprice =  0
            this.state.footerData.orderyprice = 0
            this.state.footerData.cxreductions = 0
            cartList.map((item, i) => {
                if(item.select){
                    this.state.footerData.settleNum += item.num
                    this.state.cids += item.cartId + ','
                    this.state.footerData.orderprice +=    parseFloat(item.curTotalPrice)
                    this.state.footerData.orderyprice +=   parseFloat(item.preTotalPrice)
                    this.state.footerData.cxreductions +=  parseFloat(item.disTotalPrice)
                }
            })
            
            this.setCartData(this.state.selectAllStatus,this.state.cartList)
        })
    }
    // 设置购物车数据
    setCartData(selectAllStatus,cartList) {
        if(this.state.cids.lastIndexOf(',')  ==  (this.state.cids.length - 1)){
            this.state.cids = this.state.cids.substr(0, this.state.cids.length - 1)
        }
        if (this.state.cids == '') {
            const footerData = {
                SaleUseInteger: '0', 
                cqsje: '0.00',
                cxreductions: '0.00', 
                dbje: '0.00', 
                orderprice: '0.00', 
                orderyprice: '0.00', 
                settleNum: 0, 
            }
            this.setState({
                cartList: cartList,
                selectAllStatus: selectAllStatus,
                footerData: footerData,
                cids: '',
            })
        } else {
            common.getUserCart(this, this.state.cids, (res) => {
                 console.log(res)
                this.setState({
                    cartList: cartList,
                    selectAllStatus: selectAllStatus,
                    cids: this.state.cids,
                })
            })
        }
    }
    // 点击删除
    delCart(good,index){
        common.delCart(good.N_OC_ID,(res) => {
            base.showToast(res.msg)
            this.state.cartList.splice(index,1)
            this.state.footerData.settleNum = 0
            this.state.cids = ''
            this.state.footerData.orderprice =  0
            this.state.footerData.orderyprice = 0
            this.state.footerData.cxreductions = 0
            this.state.cartList.map((item, i) => {
                if(item.select){
                    this.state.footerData.settleNum += item.num
                    this.state.cids += item.cartId + ','
                    this.state.footerData.orderprice +=   parseFloat(item.curTotalPrice)
                    this.state.footerData.orderyprice +=  parseFloat(item.preTotalPrice)
                    this.state.footerData.cxreductions += parseFloat(item.disTotalPrice)
                }
            })
            this.setCartData(this.state.selectAllStatus,this.state.cartList)
        })
    }
    // 跳首页、商品详情
    navTo(page,id) {
        if(page == 'index'){
            Taro.reLaunch({ url: '/pages/index/index' })
        }
        if(page == 'goodsDatil'){
            Taro.navigateTo({url: `/pages/goodsDatil/index?goodsId=${id}&SaleTypeNo=0`})
        } 
    }
    // 编辑、完成
    editTap() {
        this.setState({ editState: !this.state.editState })
    }
    // 结算、删除
    footBtn(obj){
        this.state.cids = ''
        this.state.footerData.orderprice =  0
        this.state.footerData.orderyprice = 0
        this.state.footerData.cxreductions = 0
        let cidsArr = []
        this.state.cartList.map((item, i) => {
            if(item.select){
                this.state.cids += item.cartId + ','
                cidsArr.push(item.cartId)
            }
        })
        this.state.cids = this.state.cids.substr(0, this.state.cids.length - 1)
        if(this.state.editState){ //编辑时--删除
            for(let j = 0;j < cidsArr.length;j++){
                this.state.cartList = this.state.cartList.filter(item => item.cartId !== cidsArr[j])
            }
            common.delCart(this.state.cids,(res) => {
                base.showToast(res.msg)
                this.state.footerData.settleNum = 0
                this.state.cids = ''
                this.state.cartList.map((item, i) => {
                    if(item.select){
                        this.state.footerData.settleNum += item.num
                        this.state.cids += item.cartId + ','
                        this.state.footerData.orderprice +=   parseFloat(item.curTotalPrice)
                        this.state.footerData.orderyprice +=   parseFloat(item.preTotalPrice)
                        this.state.footerData.cxreductions +=  parseFloat(item.disTotalPrice)
                    }
                })
                this.setCartData(this.state.selectAllStatus,this.state.cartList)
            })
        }else{ //结算
            if (this.state.cids != "") {
                Taro.navigateTo({
                    url: '/pages/orderSubmitMarketing/index?cids=' + this.state.cids + '&&totalNum=' + this.state.footerData.settleNum,
                })
            } else {
                base.showToast('请先选择商品','none')
            }
        }
    }

    render() {
        return (
            <View className='mainCart'>
                {this.state.HasCartList &&
                    <Block>
                        {this.state.cartList.length > 0 &&
                            <Block>
                                <View className='weui-cell bg-white'>
                                    <View className='weui-cell__hd'>
                                        <View className='checkboxbar'>
                                            <Checkboxbar select={this.state.selectAllStatus} onSelectCheck={this.selectCheck.bind(this, 'all')}></Checkboxbar>
                                        </View>
                                    </View>
                                    <View className='weui-cell__bd'><Text>{this.props.shopInfo.c_name}</Text></View>
                                    <View className='weui-cell__ft text-small'>
                                        <Text className='iconfont icon-tips'></Text>
                                        <Text className='text-gray'>不含运费</Text>
                                        <View className='iblock store-line'>
                                            <Text className={this.state.editState ? 'text-sub' : 'text-gray'} onClick={this.editTap}>{this.state.editState ? '完成' : '编辑'}</Text>
                                        </View>
                                    </View>
                                </View>
                                <View className='weui-cells weui-cells-none'>
                                    {this.state.cartList && this.state.cartList.map((item, i) => (
                                        <View key={'cartList' + i}>
                                            <View className='weui-cell'>
                                                <View className='weui-cell__hd'>
                                                    <View className='checkboxbar'>
                                                        <Checkboxbar select={item.select} onSelectCheck={this.selectCheck.bind(this, i)}></Checkboxbar>
                                                    </View>
                                                </View>
                                                <View className='weui-cell__bd'>
                                                    <View className='weui-flex'>
                                                        <View className='item-img-box' onClick={this.navTo.bind(this, 'goodsDatil', item.goodsId)}>
                                                            <Image className='item-img' src={this.state.domainImg + item.imageUrl}></Image>
                                                            {item.salemodelIndex &&<Text className='item-saletype'>{item.saledata[item.salemodelIndex].SaleType}</Text>}
                                                        </View>
                                                        <View className='weui-flex__item'>
                                                            <View className='item-title text-default clamp' onClick={this.navTo.bind(this, 'goodsDatil', item.goodsId)}>{item.goodsName}</View>
                                                            <View className='item-tag text-little text-gray ellipsis'>{item.C_GOODSATTR}</View>
                                                            <View className='weui-flex item-footer'>
                                                                <View className='weui-flex__item'>
                                                                    {this.state.editState ?
                                                                        <Text className='del-btn text-small' onClick={this.delCart.bind(this,item,i)}>删除</Text> : 
                                                                        <Price cartItem={item} class-pl="pl20"></Price>
                                                                    }
                                                                </View>
                                                                <View className='item-count'>
                                                                    <NumberInput type='square' onChangeCartNum={this.changeCartNum.bind(this,i)} nums={item.num} cart='true'> </NumberInput> 
                                                                </View>
                                                            </View>
                                                        </View>
                                                    </View>
                                                </View>
                                            </View>
                                            <View className='activejson text-gray text-small' onClick={this.changeSaledata.bind(this,i)}>
                                                {!item.salemodelIndex && <Text>无活动</Text>}
                                                {item.saledata && item.salemodelIndex && <Text>已选活动</Text>}
                                                <Text className='pl20'>{item.salemodelIndex ? item.saledata[item.salemodelIndex].SaleName : ''}</Text>
                                            </View>
                                        </View>
                                    ))}
                                </View>
                                <View className='footer'>
                                    <Footer selectAllStatus={this.state.selectAllStatus} editState={this.state.editState} footerData={this.state.footerData} onSelectCheck={this.selectCheck.bind(this, 'all') } onFootBtn={this.footBtn.bind(this)}></Footer>
                                </View>
                            </Block>
                        }
                        {this.state.cartList.length == 0 && <View className='empty-box text-gray ac'>购物车是空的，先去随便<Text className='text-sub nav-to' onClick={this.navTo.bind(this,'index')}>逛逛</Text>吧</View>}
                    </Block>
                }
                <Authorize page='shopcart' onSetUserInfo={this.getIsLogin.bind(this)}></Authorize>
            </View>
        )
    }
}

